<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>
  <body>
    <div id="root">
      <h2>人员列表</h2>
      <input type="text" placeholder="请输入名字" v-model="keyWord" />
      <ul>
        <li v-for="(val,ind) in filledPersons" :key="val.id">{{ind}} {{val.name}} {{val.age}}</li>
      </ul>
    </div>
    <script type="text/javascript">
      Vue.config.productionTip = false;
      // 用watch实现过滤
      // const vm = new Vue({
      //   data: {
      //     keyWord: "",
      //     persons: [
      //       { id: "001", name: "马冬梅", age: 18, sex: "女" },
      //       { id: "002", name: "周冬雨", age: 19, sex: "女" },
      //       { id: "003", name: "周杰伦", age: 25, sex: "男" },
      //       { id: "004", name: "妖伦", age: 25, sex: "男" },
      //     ],
      //     filledPersons: [],
      //   },

      //   watch: {
      //     keyWord: {
      //       immediate: true, // 直接调一次，相当于过滤一个空串，立即让所有persons元素都满足，都加入filledPersons
      //       handler(newVal, oldVal) {
      //         this.filledPersons = this.persons.filter((p) => {
      //           return p.name.indexOf(newVal) !== -1;
      //         });
      //       },
      //     },
      //   },
      // });

      // 用computed实现过滤
      const vm = new Vue({
        data: {
          keyWord: "",
          persons: [
            { id: "001", name: "马冬梅", age: 18, sex: "女" },
            { id: "002", name: "周冬雨", age: 19, sex: "女" },
            { id: "003", name: "周杰伦", age: 25, sex: "男" },
            { id: "004", name: "妖伦", age: 25, sex: "男" },
          ],
        },
        // 当computed好watch都能实现的时候，优先使用computed
        computed: {
          filledPersons: {
            get() {
              return (this.persons.name = this.persons.filter((p) => {
                return p.name.indexOf(this.keyWord) !== -1;
              }));
            },
          },
        },
      });
      vm.$mount("#root");
    </script>
  </body>
</html>
